<template>
  <ex-dialog width="800px" class="ex-diolog" :title="title" :visible="visible" @closeDialog="handleClose">
    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
      <el-form-item label="客户名称：" prop="clientName">
        <el-input type="text" v-model="ruleForm.clientName" autocomplete="off" placeholder="请填写客户名称"></el-input>
      </el-form-item>
      <el-form-item label="行业类型：" prop="industryType">
        <el-select v-model="ruleForm.industryType" filterable placeholder="请选择行业类型">
          <el-option v-for="item in industryTypeList" :key="item.id" :label="item.value" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间：" prop="createTime">
        <el-date-picker v-model="ruleForm.createTime" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" :picker-options="pickerOptions">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="客户地址：" prop="customerAddress">
        <el-cascader v-model="ruleForm.customerAddress" :options="cityList"
          :props="{ value: 'id', label: 'label', children: 'children' }" @change="regionChange" style="width:240px;"></el-cascader>
      </el-form-item>
      <el-form-item label="详细地址：" prop="address">
        <el-input type="text" v-model="ruleForm.address" autocomplete="off" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="门店数量：" prop="shopNum">
        <el-input type="text" v-model="ruleForm.shopNum" autocomplete="off" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="客户对接人：" prop="contactPerson">
        <el-input type="text" v-model="ruleForm.contactPerson" autocomplete="off" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="联系方式：" prop="phone">
        <el-input type="text" v-model="ruleForm.phone" autocomplete="off" maxlength="50" placeholder="请输入"></el-input>
      </el-form-item>

      <el-form-item label="客户类型：" prop="clientType" class="numericalValue">
        <el-radio-group v-model="ruleForm.clientType">
          <el-radio v-for="(item) in clientTypeList" :label="item.id" :key="item.id">{{ item.value }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="客户级别：" prop="clientLevel" class="numericalValue">
        <el-radio-group v-model="ruleForm.clientLevel">
          <el-radio v-for="(item) in clientLevelList" :label="item.id" :key="item.id">{{ clientTypeListName[item.id - 1] }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="客户诉求：" prop="appealList">
        <el-checkbox-group v-model="ruleForm.appealList" @change="changeAppealList">
          <el-checkbox v-for="(item, index) in appealListArray" :key="index"
            :label="item.id">{{ item.value }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="其他诉求：" prop="otherAppeal" v-if="isOther">
        <el-input type="text" v-model="ruleForm.otherAppeal" autocomplete="off" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="抖音来客账号：" prop="tiktokVisitorAccount">
        <el-input type="text" v-model="ruleForm.tiktokVisitorAccount" autocomplete="off"
          placeholder="是否注册过抖音来客，有就写，没有就写待注册"></el-input>
      </el-form-item>
      <el-form-item label="客户负责人：" prop="responsibleIdList">
        <el-select v-model="ruleForm.responsibleIdList" multiple filterable placeholder="请选择" style="width:350px;">
          <el-option v-for="item in responsibleIdListArray" :key="item.id" :label="item.value"
            :value="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')" :loading="loading">保存提交</el-button>
        <el-button @click="handleClose('ruleForm')">取消</el-button>
      </el-form-item>
    </el-form>
  </ex-dialog>
</template>
<script>
// components
import Loading from '@/components/Loading/index'
// api
import {
  addClientFiling,
  editClientFiling,
  clientFilingDetail,
  responsibleSelect
} from "@/api/customer/reportingForm";
import { getCity } from "@/api/clientManagement";
export default {
  components: {
    Loading
  },
  props: {
    visible: Boolean,
    id: String,
    pathType: String,
  },
  data() {
    const checkShopNum = (rule, value, callback) => {
        if (value) {
          var reg = /^\+?[1-9]\d*$/
          // var reg = /^\+?[0-9][0-9]*$/; //大于等于0的正整数
          if (reg.test(value) === false) {
            callback(new Error('请输入大于0的整数'))
            // callback(new Error('请输入大于等于0的正整数'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
    return {
      loading: false,
      title: '创建客户资料',
      cityList: [], //省市区
      industryTypeList: [],//行业类型
      clientTypeList: [],//客户类型人列表
      clientLevelList: [],//客户级别列表
      appealListArray: [],//客户诉求列表
      responsibleIdListArray: [],//客户负责人列表
      // 客户级别名称
      clientTypeListName: [
        'S 门店数大于等于100家/线上月度销售额大于等于250万元',
        'A 门店数大于等于20家/线上月度销售额小于250万，大于等于70万元',
        'B 门店数小于等于10家/线上月度销售额小于70万元，大于等于10万',
        'C 门店数小于等于3家/线上月度销售额小于10万元，大于等于3万',
        '渠道运营商'
      ],
      isOther:false,//是否选择其他诉求
      ruleForm: {
        clientName: '',//客户名称
        industryType: '',//行业类型
        createTime: '',//创建时间
        customerAddress: '',//客户地址
        province: '',//省
        city: '',//市
        area: '',//区
        address: '',//详细地址
        shopNum: '',//门店数量
        contactPerson: '',//客户对接人
        phone: '',//联系方式
        clientType: '',//客户类型
        clientLevel: '',//客户级别
        appealList: [],//客户诉求
        otherAppeal: '', // 其他诉求
        tiktokVisitorAccount: '', // 抖音来客账号
        responsibleIdList: [], // 客户负责人
      },
      rules: {
        clientName: [
          { required: true, message: '请填写客户名称', trigger: 'blur' }
        ],
        industryType: [
          { required: true, message: '请选择行业类型', trigger: 'change' }
        ],
        createTime: [
          { required: true, message: '请选择创建时间', trigger: 'change' }
        ],
        customerAddress: [
          { required: true, message: '请选择客户地址', trigger: 'change' }
        ],
        address: [
          { required: true, message: '请填写详细地址', trigger: 'blur' }
        ],
        shopNum: [
          { required: true, message: '请填写门店数量', trigger: 'blur' },
          { required: true,validator: checkShopNum,trigger: 'blur' }
        ],
        contactPerson: [
          { required: true, message: '请填写客户对接人', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请填写联系方式', trigger: 'blur' },
        ],
        clientType: [
          { required: true, message: '请选择客户类型', trigger: 'change' }
        ],
        clientLevel: [
          { required: true, message: '请选择客户级别', trigger: 'change' }
        ],
        appealList: [
          { required: true, message: '请选择客户诉求', trigger: 'change' }
        ],
        otherAppeal: [
          { required: true, message: '请填写其他诉求', trigger: 'blur' }
        ],
        tiktokVisitorAccount: [
          { required: true, message: '请填写抖音来客账号', trigger: 'blur' }
        ],
        responsibleIdList: [
          { required: true, message: '请选择客户负责人', trigger: 'change' }
        ],
        // minBetAmount: [
        //   { required: true,validator: validateMinBetAmount,trigger: 'blur' }
        // ],
      },
      pickerOptions: {
          disabledDate(time) {
              return time.getTime() >= Date.now(); 
          }
        }
    }
  },
  computed: {

  },
  created() {
    this.getStatusList();
    this.getResponsiblePersonIdList()
    this.getCity();
    if (this.pathType == 'edit') {
      this.title = '编辑客户资料'
      this.getDetail()
    } else if (this.pathType == 'add') {
      this.title = '创建客户资料'
      this.ruleForm.id = ''
    }

  },
  methods: {
    // 其他诉求改变
    changeAppealList(){
      this.isOther = this.ruleForm.appealList.find(obj => obj == 5)?true:false
    },
    // 获取活动状态字典
    getStatusList() {
      var dictType = "bee_client_industry_type,bee_client_type,bee_client_level,bee_client_filing_appeal";
      this.$getSelectList(dictType)
        .then((res) => {
          this.industryTypeList = res.result[0].dictList
          this.clientTypeList = res.result[1].dictList
          this.clientLevelList = res.result[2].dictList
          this.appealListArray = res.result[3].dictList
        })
        .finally(() => { });
    },
    // 客户负责人下拉
    getResponsiblePersonIdList() {
      responsibleSelect().then((res) => {
        console.log('res',res.result)
        this.responsibleIdListArray = res.result
      })
    },
    //城市区域选择
    regionChange(value) {
      this.ruleForm.province = value[0];
      this.ruleForm.city = value[1];
      this.ruleForm.area = value[2];
    },
    //查询城市数据
    getCity() {
      const params = {};
      getCity(params)
        .then((res) => {
          //   this.options = res.result;
          this.cityList = res.result;
          this.cityList.forEach((item) => {
            item.children.forEach((items) => {
              items.children.forEach((itemss) => {
                if (itemss.children.length == 0) {
                  itemss.children = null
                }
              })
            })
          })
        })
        .finally(() => { });
    },
    //获取详情
    getDetail() {
      var id = this.id
      console.log('id', id)
      clientFilingDetail(id).then(res => {
        this.ruleForm = res.result
        //处理客户地址回显
        let regionAvalue = [];
        regionAvalue.push(this.ruleForm.province);
        regionAvalue.push(this.ruleForm.city);
        regionAvalue.push(this.ruleForm.area);
        this.ruleForm.customerAddress = regionAvalue;
        console.log('this.ruleForm.appealList.find(obj => obj == 6)',this.ruleForm.appealList.find(obj => obj == 5))
        console.log('this.ruleForm.appealList',this.ruleForm.appealList)
        this.isOther = this.ruleForm.appealList.find(obj => obj == 5)?true:false
      })
    },
    // 提交表单
    submitForm(formName) {
      console.log('formName', formName)
      this.$refs[formName].validate((valid) => {
        console.log('valid', valid)
        if (valid) {
          if (this.pathType == 'add') {
            this.createCustomer()
          } else if (this.pathType == 'edit') {
            this.editCustomer()
          }

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 创建客户
    createCustomer() {
      this.loading = true
      var data = {
        ...this.ruleForm
      }
      if(!this.isOther){
        data.otherAppeal = ''
      }
      addClientFiling(data).then(res => {
        this.$message.success('添加成功')
        setTimeout(() => {
          this.handleClose()
          this.$emit('success')
          this.loading = false
        }, 1000);
      }).catch(() => {
        this.loading = false
      })
    },
    // 编辑客户
    editCustomer() {
      this.loading = true
      var data = {
        ...this.ruleForm
      }
      if(!this.isOther){
        data.otherAppeal = ''
      }
      editClientFiling(data).then(res => {
        this.$message.success('修改成功')
        setTimeout(() => {
          this.handleClose()
          this.$emit('success')
          this.loading = false
        }, 1000);
      }).catch(() => {
        this.loading = false
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

    //取消
    handleClose(formName) {
      this.$emit('update:visible', false)
      // this.$refs[formName].resetFields();
    },
  }
}
</script>
<style lang="scss" scoped>
.ex-diolog {
  ::v-deep {
    .ex--dialog--footer {
      border: none !important;
      padding: 0 !important;
    }

    .ex--dialog--main {
      padding: 10px 20px !important;
    }
    .numericalValue {
      .el-form-item__content {
        margin-top: 12px;
        .el-radio-group {
          display: flex;
          flex-direction: column;
          .el-radio {
            margin-bottom: 17px;
          }
        }
      }
    }
    .el-checkbox-group{
      display: flex;
      flex-direction: column;
    }
  }
}

.el-input {
  width: 350px;
}
</style>